<template>
  <div style="height: 100%; width: 100%; overflow-x: auto;">
    <h3 style="margin-bottom: 20px;">药品信息管理</h3>

    <el-table
        :key="tableKey"
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px;"
        :height="tableHeight"
        :row-style="{ height: '50px' }"
        :cell-style="{ padding: '0' }"
    >
      <el-table-column
          prop="name"
          label="药品名称"
          min-width="120px"
      ></el-table-column>

      <el-table-column
          prop="method"
          label="常见使用说明"
          min-width="200px"
      >
        <template v-slot:default="scope">
          <div class="text-wrap">{{ scope.row.method }}</div>
        </template>
      </el-table-column>

      <el-table-column
          prop="remark"
          label="药品备注"
          min-width="200px"
      >
        <template v-slot:default="scope">
          <div class="text-wrap">{{ scope.row.remark }}</div>
        </template>
      </el-table-column>

      <el-table-column
          label="管理"
          min-width="150px"
          fixed="right"
      >
        <template v-slot:header>
          <el-button
              type="primary"
              size="small"
              @click="handleAdd"
              style="float: right;"
          >
            增加
          </el-button>
          <span>管理</span>
        </template>
        <template v-slot:default="scope">
          <el-button
              :type="scope.row.isused === '启用' ? 'success' : 'danger'"
              size="small"
              @click="handleToggleUse(scope.row)"
          >
            {{ scope.row.isused }}
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin-top: 10px;">
      <el-col :span="24" style="text-align: right;">
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- 添加药品对话框 -->
    <el-dialog
        title="添加药品"
        v-model="addDialogVisible"
        width="500px"
        @close="resetAddForm"
    >
      <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="100px">
        <el-form-item label="药品名称" prop="name">
          <el-input
              v-model="addForm.name"
              placeholder="请输入药品名称"
              maxlength="255"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="常见使用说明" prop="method">
          <el-input
              v-model="addForm.method"
              type="textarea"
              :rows="3"
              placeholder="请输入常见使用说明"
              maxlength="255"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="药品备注" prop="remark">
          <el-input
              v-model="addForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入药品备注"
              maxlength="255"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">提交</el-button>
      </template>
    </el-dialog>

    <!-- 修改药品对话框 -->
    <el-dialog
        title="修改药品"
        v-model="editDialogVisible"
        width="500px"
        @close="resetEditForm"
    >
      <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="100px">
        <el-form-item label="药品名称" prop="name">
          <el-input
              v-model="editForm.name"
              placeholder="请输入药品名称"
              maxlength="255"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="常见使用说明" prop="method">
          <el-input
              v-model="editForm.method"
              type="textarea"
              :rows="3"
              placeholder="请输入常见使用说明"
              maxlength="255"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="药品备注" prop="remark">
          <el-input
              v-model="editForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入药品备注"
              maxlength="255"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { apiClient } from '../api/apiClient.ts'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Yaopingxinxi',
  data() {
    return {
      tableKey: 0,
      page: 1,
      size: 10,
      total: 0,
      allData: [],
      tableData: [],
      tableHeight: 'calc(100% - 120px)',

      // 添加药品相关
      addDialogVisible: false,
      addForm: {
        name: '',
        method: '',
        remark: ''
      },

      // 修改药品相关
      editDialogVisible: false,
      editForm: {
        id: '',
        name: '',
        method: '',
        remark: ''
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '药品名称不能为空', trigger: 'blur' }
        ],
        method: [
          { required: true, message: '常见使用说明不能为空', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '药品备注不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取药品数据
    fetchData() {
      apiClient.get('/patient/getAllDrug')
          .then(response => {
            if (response.data.code === 1) {
              this.allData = response.data.data || [];
              this.total = this.allData.length;
              this.getTableData();
            } else {
              ElMessage.error('获取药品数据失败: ' + (response.data.msg || '未知错误'));
              this.allData = [];
              this.total = 0;
              this.tableData = [];
            }
          })
          .catch(error => {
            console.error('获取药品信息失败:', error);
            ElMessage.error('网络请求失败，请稍后重试');
          });
    },

    // 获取当前页数据
    getTableData() {
      const startIndex = (this.page - 1) * this.size;
      const endIndex = startIndex + this.size;
      this.tableData = this.allData.slice(startIndex, endIndex);
      this.tableKey++;
    },

    // 页码大小变化
    sizeChange(newSize) {
      this.size = newSize;
      this.page = 1;
      this.getTableData();
    },

    // 当前页码变化
    currentChange(newPage) {
      this.page = newPage;
      this.getTableData();
    },

    // 处理启用/禁用
    handleToggleUse(row) {
      const newStatus = row.isused === '启用' ? '禁用' : '启用';
      const confirmMessage = row.isused === '启用'
          ? `您确定禁用药品"${row.name}"吗？`
          : `您确定启用药品"${row.name}"吗？`;

      const successMessage = row.isused === '启用'
          ? `您已成功禁用药品"${row.name}"`
          : `您已成功启用药品"${row.name}"`;

      ElMessageBox.confirm(confirmMessage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.id,
          isused: newStatus
        };

        apiClient.post('/patient/changeDrugUse', params)
            .then(response => {
              if (response.data.code === 1) {
                ElMessage.success(successMessage);
                this.fetchData(); // 重新加载数据
              } else {
                ElMessage.error('操作失败: ' + (response.data.msg || '未知错误'));
              }
            })
            .catch(error => {
              console.error('启用/禁用药品失败:', error);
              ElMessage.error('系统错误，请稍后重试');
            });
      }).catch(() => {
        // 用户取消操作
      });
    },

    // 处理添加药品
    handleAdd() {
      this.addDialogVisible = true;
    },

    // 提交添加表单
    submitAddForm() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('您确定添加该药品吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = {
              name: this.addForm.name,
              method: this.addForm.method,
              remark: this.addForm.remark
            };

            apiClient.post('/patient/addDrug', params)
                .then(response => {
                  if (response.data.code === 1) {
                    ElMessage.success(response.data.msg || '添加药品成功');
                    this.addDialogVisible = false;
                    this.fetchData(); // 重新加载数据
                  } else {
                    ElMessage.error('添加失败: ' + (response.data.msg || '未知错误'));
                  }
                })
                .catch(error => {
                  console.error('添加药品失败:', error);
                  ElMessage.error('系统错误，请稍后重试');
                });
          }).catch(() => {
            // 用户取消操作
          });
        } else {
          ElMessage.error('请完善表单信息');
          return false;
        }
      });
    },

    // 重置添加表单
    resetAddForm() {
      this.$refs.addFormRef.resetFields();
    },

    // 处理修改药品
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        name: row.name,
        method: row.method,
        remark: row.remark
      };
      this.editDialogVisible = true;
    },

    // 提交修改表单
    submitEditForm() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('您确定修改该药品吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = {
              id: this.editForm.id,
              name: this.editForm.name,
              method: this.editForm.method,
              remark: this.editForm.remark
            };

            apiClient.post('/patient/changeDrug', params)
                .then(response => {
                  if (response.data.code === 1) {
                    ElMessage.success(response.data.msg || '修改药品成功');
                    this.editDialogVisible = false;
                    this.fetchData(); // 重新加载数据
                  } else {
                    ElMessage.error('修改失败: ' + (response.data.msg || '未知错误'));
                  }
                })
                .catch(error => {
                  console.error('修改药品失败:', error);
                  ElMessage.error('系统错误，请稍后重试');
                });
          }).catch(() => {
            // 用户取消操作
          });
        } else {
          ElMessage.error('请完善表单信息');
          return false;
        }
      });
    },

    // 重置修改表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields();
    }
  }
};
</script>

<style scoped>
.text-wrap {
  white-space: pre-wrap;
  line-height: 1.5;
  max-height: 120px;
  overflow: auto;
  letter-spacing: normal;
  --characters-per-line: 22;
  width: calc(var(--characters-per-line) * 1ch);
  min-height: 48px;
  display: block;
}
h3 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
</style>